# -*- coding: utf-8 -*-
import top.api
import sys
import requests
import re

reload(sys)
sys.setdefaultencoding('utf-8')

category_list = [
    '女士内衣/男士内衣/家居服',
    '男装',
    '女装/女士精品',
    '零食/坚果/特产',
    '3C数码配件',
    '家居饰品',
    '洗护清洁剂/卫生巾/纸/香薰',
    '尿片/洗护/喂哺/推车床',
    '童装/婴儿装/亲子装'
]


def get_tao_key(text, url, logo):
    req = top.api.TbkTpwdCreateRequest()
    req.set_app_info(top.appinfo("24652066", "fea4abb685d2e39140dc50764f943d05"))
    req.text = text
    req.url = url
    req.logo = logo
    resp = req.getResponse()
    try:
        return resp['tbk_tpwd_create_response']['data']['model']
    except KeyError:
        return None


def get_baidu_short_url(url):
    req_url = 'http://dwz.cn/create.php'
    data = {
        'url': url,
        'access_type': 'web'
    }
    resp = requests.post(req_url, data)
    if resp.status_code == 200 and resp.json()['status'] == 0:
        print(resp.json()['tinyurl'])
        return resp.json()['tinyurl']
    return ''


def get_short_url(url):
    req_url = 'http://w2wz.com/?url=' + url
    resp = requests.get(req_url)
    results = re.findall(r'<strong><a href="(.*)" target="_blank"', resp.text)
    if results is not None and len(results) > 0:
        return results[0]
    return ''

def get_item_detail(num_id):
    req = top.api.TbkItemInfoGetRequest()
    req.set_app_info(top.appinfo("24652066", "fea4abb685d2e39140dc50764f943d05"))

    req.fields = "num_iid,title,cat_name"
    req.platform = 1
    req.num_iids = num_id
    try:
        resp = req.getResponse()
        return resp['tbk_item_info_get_response']['results']['n_tbk_item'][0]['cat_name']
    except ValueError:
        pass


def get_list_item(page_no):
    req = top.api.TbkDgItemCouponGetRequest()
    req.set_app_info(top.appinfo("24652066", "fea4abb685d2e39140dc50764f943d05"))
    req.adzone_id = 178188394
    req.platform = 2
    req.page_size = 1
    req.page_no = page_no
    try:
        resp = req.getResponse()
        if resp['tbk_dg_item_coupon_get_response']['total_results'] > 0:
            uatm_tbk_items = resp['tbk_dg_item_coupon_get_response']['results']['tbk_coupon']
            for item in uatm_tbk_items:
                if item['volume'] > 1000 and item['commission_rate'] > 30 and item[
                    'coupon_remain_count'] > 0 and get_item_detail(item['num_iid']) in category_list:
                    key = get_tao_key(item['title'].encode('utf-8'), item['coupon_click_url'].encode('utf-8'),
                                      item['pict_url'].encode('utf-8'))
                    content = "#每天白菜价优惠#" + item['title'].encode('utf-8') + "\n领券：" + get_short_url(
                        item['coupon_click_url']) + "\n复制，" + key + "，用手*机*淘*宝打开\n更多优惠上『白菜价网』戳 http://baicaijia.wang|" + \
                              item['pict_url'].encode('utf-8') + '|' + str(item['num_iid'])
                    print(content)
                    return content
        return None
    except ValueError:
        return None

get_list_item(int(sys.argv[1]))
